package com.smartsofa.fragment;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.smartsofa.R;
import com.smartsofa.entity.User;
import com.smartsofa.main.HistoryActivity;
import com.smartsofa.util.CusorProgressBar;
import com.smartsofa.util.MyUtils;
import com.smartsofa.util.RoundProgressBar;
import com.smartsofa.util.ScoreStipulate;

public class AssessFragment extends Fragment{
	private FragmentActivity mActivity;
	private View mParent;
	private RoundProgressBar mRoundProgressBar;
	private RoundProgressBar roundProgressBar;
	private Paint mLinePaint;
    private Button bt_history;
    private CusorProgressBar xueya;
    private CusorProgressBar xuetang;
    private CusorProgressBar xueyang;
	private String url;
	private ProgressDialog mDialog;	
	private Boolean flag=false;
	Intent intent;
	private PullToRefreshListView pullToRefresh;//实现下拉刷新与上拉加载的ListView	
	private float SBP;
	private float DBP;
	private float BG;
	private float BOS;
	private View layout_assess;
	private TextView healthComments;
	
	private JSONObject json;
	
	//定义网络连接超时判定变量
	private boolean network_timeout=false;

    User user=new User();
    
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.fragment_assess, container,false);	
		bt_history=(Button) view.findViewById(R.id.bt_history);
		layout_assess = view.findViewById(R.id.layout_assess);
		return view;
    }

	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mActivity = getActivity();  
	    mParent = getView();    
//	    user.setUserId(mActivity.getIntent().getIntExtra("userId", 0));
	    xueyang= (CusorProgressBar) mActivity.findViewById(R.id.xueyang);
	    xueya= (CusorProgressBar) mActivity.findViewById(R.id.xueya);
	    xuetang= (CusorProgressBar) mActivity.findViewById(R.id.xuetang);
	    roundProgressBar=(RoundProgressBar) mActivity.findViewById(R.id.assess_bar);
	    healthComments = (TextView) mActivity.findViewById(R.id.tx_healthcomment);
	    bt_history= (Button) mActivity.findViewById(R.id.bt_history);
	    bt_history.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			intent= new	Intent().setClass(mActivity, HistoryActivity.class);
				startActivity(intent);				
			}
		});
		mDialog = new ProgressDialog(mActivity);
		mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mDialog.setMessage("数据加载中...");
		mDialog.show();
	    loadData();
	    pullToRefresh = (PullToRefreshListView)mActivity.findViewById(R.id.assess_pullToRefresh);     
        init(); 
        pullToRefresh.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub
				loadData();
			}  
       });				
	}
	private void init(){    
        ILoadingLayout startLabels = pullToRefresh    
                .getLoadingLayoutProxy(true, false);    
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示    
        startLabels.setRefreshingLabel("正在载入...");// 刷新时    
        startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示    
    
        ILoadingLayout endLabels = pullToRefresh.getLoadingLayoutProxy(    
                false, true);    
        endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示    
        endLabels.setRefreshingLabel("正在载入...");// 刷新时    
        endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示    
        pullToRefresh.setEmptyView(layout_assess);
    }
	private void loadData(){
		Thread thread=new Thread(new LoadDataThread());
	    thread.start();
	}
	
	class LoadDataThread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {			
				url=MyUtils.getUrl()+"display_getLatestData?userid="+MyUtils.getUSERID();
				HttpGet request = new HttpGet(url);																
		       HttpResponse httpResponse = new DefaultHttpClient().execute(request);					       		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	network_timeout=true;
		        String jsonString = EntityUtils.toString(httpResponse.getEntity());
		        json = new JSONObject(jsonString);
		        flag=(Boolean) json.get("success");		
		        
		        
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		      }
			Message msg = content_handler.obtainMessage();
			if(network_timeout){
				if (flag) {				
					msg.what = 1;									
				}else{
					msg.what = 2;			
				}
			}			
			else{
				msg.what = 3;						
			}
			content_handler.sendMessage(msg);
			}
			
		}
		Handler content_handler = new Handler() {
			public void handleMessage(Message msg) {
				mDialog.dismiss();
				pullToRefresh.onRefreshComplete(); //结束刷新
				switch (msg.what) {		
				case 1:
					try {
						JSONObject jsonobj = new JSONObject();
						jsonobj=json.getJSONObject("obj");
						SBP= Float.valueOf((float) jsonobj.getJSONObject("SBP").getDouble("dataValue"));
						DBP=  Float.valueOf((float) jsonobj.getJSONObject("DBP").getDouble("dataValue"));
						BG= Float.valueOf((float) jsonobj.getJSONObject("BG").getDouble("dataValue"));
						BOS=  Float.valueOf((float)  jsonobj.getJSONObject("BOS").getDouble("dataValue"));
						xueya.setProgress(SBP);
						xueya.setProgressb(DBP);
						xuetang.setProgress(BG);
						xueyang.setProgress(BOS);		
						ScoreStipulate mScoreStipulate = new ScoreStipulate(SBP,DBP,BG,BOS);
						roundProgressBar.setProgress(mScoreStipulate.getScore());
						healthComments.setText(mScoreStipulate.getComments());
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}		        			        
					break;
				case 2:
					healthComments.setText("您还没有上传测量数据！");
					roundProgressBar.setProgress(100);
					Toast.makeText(mActivity, "您还没有数据记录！" , Toast.LENGTH_SHORT).show();
					break;
				
				case 3:
					Toast.makeText(mActivity, "网络连接超时！", Toast.LENGTH_SHORT).show();
					break;
				}
			}
		};
			
	}				

